import React, { useEffect, useRef, useState } from "react";
import loadingURL from "./loading.gif";
import errorURL from "./error.jpeg";
interface PropsType {
  width?: string | number;
  height?: string | number;
  src: string;
}

export const LazyImage: React.FC<PropsType> = ({
  width = "100%",
  height = "auto",
  src,
}) => {
  const [url, setUrl] = useState(loadingURL);
  const img = useRef<HTMLImageElement | null>(null);
  
  const loadImage = () => {
    const img = new Image();

    img.src = src;

    img.addEventListener("load", () => {
      // setTimeout(() => {
      setUrl(src);
      // }, Math.random() * 5000);
    });

    img.addEventListener("error", () => {
      setUrl(errorURL);
    });
  };

  useEffect(() => {
    // 实验性  
    const io = new IntersectionObserver((entries) => {
      entries.forEach((v) => {
        if (v.intersectionRatio > 0) loadImage();
      });
    });

    io.observe(img.current as HTMLImageElement);
  }, []);

  return (
    <div>
      <img ref={img} src={url} alt="" width={width} height={height} />
    </div>
  );
};
